from django_tenants.utils import schema_context
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from .models import SystemAccounts, Provider, ClientSchemaHandle
from apps.core.utils import gcs_operations

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):

    @classmethod
    def get_token(cls, user):

        token = super().get_token(user)
        # Add custom claims
        token['username'] = user.username
        # token['id'] = str(user.id)
        token['is_superuser'] = user.is_superuser
        token['is_staff'] = user.is_staff
        token['is_provider'] = user.is_provider
        token['is_client'] = user.is_client
        token['email'] = user.email
        token['is_first_login'] = user.is_first_login
        token['avatar'] = user.avatar.url if user.avatar else ''
        # token['is_kiosk'] = SystemAccounts.objects.filter(id=user.id).first().values('is_kiosk') if SystemAccounts.objects.filter(id=user.id).exists() else None
        token['is_active'] = user.is_active
        token['first_name'] = user.first_name
        token['middle_name'] = user.middle_name
        token['last_name'] = user.last_name
        token['phone_number'] = user.phone_number



        if user.is_provider:
            token['schema_context'] = user.provider.schema_name if user.provider else None

        if user.is_client:
            provider = ClientSchemaHandle.objects.filter(client_id=user.id).first()
            if provider:
                token['schema_context'] = provider.schema_name if provider else None
                with schema_context(provider.schema_name):
                    token['document_get_started'] = user.client.document_get_started

        try:
            system_account = SystemAccounts.objects.filter(id=user.id).first()
            if system_account:
                token['is_kiosk'] = system_account.is_kiosk
        except SystemAccounts.DoesNotExist:
            token['is_kiosk'] = False

        try:
            system_account = SystemAccounts.objects.filter(id=user.id).first()
            if system_account:
                token['is_welcome_board'] = system_account.is_welcome_board
        except SystemAccounts.DoesNotExist:
            token['is_welcome_board'] = False

        # if user.is_provider is True:
        #     stripe = ProviderStripeAccount.objects.filter(provider=user).exists()
        #     token['stripe'] = stripe
        #
        # if user.is_client is True:
        #     token['messaging'] = user.client.messaging

        # ...

        return token
